import prisma from "@/db/prisma";
import {
  CreateLcPageResponse,
  GetLcPageByIdResponse,
  UpdateLcPageResponse,
} from "@/types/api";
import { Prisma } from "@prisma/generated-client";

export class LcPageService {
  async create(
    data: Prisma.LcPageUncheckedCreateInput
  ): Promise<CreateLcPageResponse> {
    return prisma.lcPage.create({
      data,
    });
  }

  async findOne(lcPageId: number): Promise<GetLcPageByIdResponse> {
    return prisma.lcPage.findUnique({
      where: { id: lcPageId, deletedAt: null },
    });
  }

  async update(
    lcPageId: number,
    data: Prisma.LcPageUncheckedUpdateInput
  ): Promise<UpdateLcPageResponse> {
    return prisma.lcPage.update({
      where: { id: lcPageId, deletedAt: null },
      data,
    });
  }

  async delete(lcPageId: number) {
    await prisma.lcPage.update({
      where: { id: lcPageId, deletedAt: null },
      data: { deletedAt: new Date() },
    });
    return true;
  }

  async page(
    pageNum: number,
    pageSize: number,
    keywords?: string,
    orderBy?: Prisma.LcPageCountOrderByAggregateInput
  ) {
    const where: Prisma.LcPageWhereInput = {
      deletedAt: null,
      OR: keywords
        ? [
            { title: { contains: keywords } },
            { remark: { contains: keywords } },
          ]
        : undefined,
    };

    if (!orderBy) {
      orderBy = {
        createdAt: "desc",
      };
    }

    return prisma.$transaction(async (prisma) => {
      const total = await prisma.lcPage.count({ where });
      const data = await prisma.lcPage.findMany({
        skip: (pageNum - 1) * pageSize, // 跳过 (页码 - 1) * 每页数量 的记录
        take: pageSize, // 获取 pageSize 数量的记录
        where,
        orderBy,
      });

      return { data, total };
    });
  }
}
